/**
 * 
 */
package hu.cubussapiens.facts.query;

import hu.cubussapiens.facts.Fact;

import java.util.ArrayList;
import java.util.List;

/**
 * @author balage
 *
 */
public class Select implements Query {

	final Query q1;
	final Query q2;
	final int index;
	
	/**
	 * index:
	 * 0: select object
	 * 1: select verb
	 * 2: select subject
	 */
	public Select(Query q1, Query q2, int index) {
		this.q1 = q1;
		this.q2 = q2;
		this.index = index;
	}

	/* (non-Javadoc)
	 * @see hu.cubussapiens.facts.query.Query#execute(hu.cubussapiens.facts.query.IQueryContext)
	 */
	@Override
	public List<Long> execute(IQueryContext context) {
		List<Long> q1r = q1.execute(context);
		List<Long> q2r = q2.execute(context);
		List<Long> result = new ArrayList<Long>(q1r.size()*q2r.size());
		
		for(Long a : q1r)
			for(Long b : q2r){
				javax.jdo.Query query = context.getManager().newQuery(Fact.class);
				query.setFilter(getfilter(a, b, index));
				List<?> data = (List<?>)query.execute();
				for(Object d : data){
					if (d instanceof Fact){
						Fact f = (Fact)d;
						result.add( index==0 ? f.getObjectID() : (index==1 ? f.getVerbID() : f.getSubjectID()) );
					}
				}
			}
		
		return result;
	}

	private String getfilter(Long a, Long b, int index){
		switch(index){
		case 0: return "subjectID == "+a+" && verbID == "+b;
		case 1: return "subjectID == "+a+" && objectID == "+b;
		case 2: return "objectID == "+a+" && verbID == "+b;
		}
		return null;
	}
	
}
